package com.yanqu.road.server.gameplayer.module.union.cross;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.task.args.union.UnionActivityTaskArgs;
import com.yanqu.road.entity.union.*;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.cross.CrossUnionChamberPatrons;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.logic.bussiness.union.UserUnionBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.pb.activity.RecoveryRewardProto;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tomb.TombMgr;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.TradeWarActivityMgr;
import com.yanqu.road.server.manger.activity.fivehero.FiveHeroMgr;
import com.yanqu.road.server.manger.activity.hanghai.HangHaiMgr;
import com.yanqu.road.server.manger.activity.langyabang.LangYaBangMgr;
import com.yanqu.road.server.manger.activity.orewar.OreWarActivityMgr;
import com.yanqu.road.server.manger.activity.peakseacraft.PeakSeacraftMgr;
import com.yanqu.road.server.manger.activity.peakstronghold.PeakStrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.rankunionwar.RankUnionWarMgr;
import com.yanqu.road.server.manger.activity.seacraft.SeacraftPirateRiotMgr;
import com.yanqu.road.server.manger.activity.seacraft.SeacraftSouthSeaMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.tonbing.TonBingMgr;
import com.yanqu.road.server.manger.activity.tonbingchannel.ChannelTonBingMgr;
import com.yanqu.road.server.manger.activity.tongbing.TongBingMgr;
import com.yanqu.road.server.manger.activity.twins.TwinsMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionPhaseWarMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.UnionPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class CrossUnionModule extends GeneralModule {

    private UserUnionChamberData userUnionChamberData;

    public CrossUnionModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        userUnionChamberData = UserUnionBussiness.getUserUnionChamberData(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.Union.getValue())){
            initUserChamberData();
        }
        return true;
    }

    @Override
    public boolean saveData() {
        if(null != userUnionChamberData){
            if(userUnionChamberData.isInsertOption()){
                UserUnionBussiness.addUserUnionChamberData(userUnionChamberData);
            }else if(userUnionChamberData.isUpdateOption()){
                UserUnionBussiness.updateUserUnionChamberData(userUnionChamberData);
            }
        }
        return true;
    }

    @Override
    public void loginSendMsg() {
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.MonthRankGradeCacheLevel,0);
    }

    @Override
    public void afterLogin() {
        String unionUid = player.getUserInfo().getUnionUid();
        CrossUnionMember member = CrossUnionMgr.getUnionMember(unionUid, player.getUserId());
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            if (null != member) {
                if (member.getPosition() == eUnionPosition.Master.getValue() || member.getPosition() == eUnionPosition.DeputyMaster.getValue()) {
                    //UnionJoinApplyMgr.sendJoinApplyList(player, unionUid);
                }
                //player.sendChannelPacket(Protocol.U_UNION_DETAIL, UnionMgr.getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue()));
            }
            UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if(null != unionInfo){
                if(null != member){
                    if(member.getChamberPatronsId() > 0){
                        UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(member.getChamberPatronsId());
                        if(null != userPatrons){
                            //member.setChamberPatron(userPatrons);
                            //member.setChamberPatrons();
                        }
                    }
                }
                syncChamberPatronsList();
            }
        } else {
            if (member != null) {
                //syncUnionMember(member);
            }
        }
        syncChamberData();
        CrossUnionProto.CrossUnionMemberLoginReqMsg.Builder crossReq = CrossUnionProto.CrossUnionMemberLoginReqMsg.newBuilder();
        crossReq.setUnionUid(unionUid);
        UserHistoryAttribute historyAttribute = player.getModule(PlayerModule.class).getUserHistoryAttribute();
        if (null != historyAttribute){
            crossReq.setHistoryMaxAbility(historyAttribute.getAbility().toString());
        }
        crossReq.setPlayerBaseData(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
        player.sendPacket(Protocol.C_CROSS_UNION_AFTER_LOGIN, crossReq);

        syncGroup();
    }

    public void syncGroup(){
        CrossUnionServerGroup serverGroup = CrossUnionServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        CrossUnionProto.UnionServerGroupSyncMsg.Builder syncMsg = CrossUnionMgr.buildCrossUnionGroup(serverGroup);
        player.sendPacket(Protocol.U_UNION_CROSS_GROUP_SYNC, syncMsg);
    }

    public void resetOneDay(){
        if(null != userUnionChamberData){
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
            if(zeroTime > userUnionChamberData.getLastResetTime()){
                userUnionChamberData.setUseHuntUserIdList(new ArrayList<>());
                userUnionChamberData.setLastResetTime(zeroTime);
                syncChamberData();
            }
        }
    }

    public void initSystem(){
        initUserChamberData();
        syncChamberData();
    }

    private void initUserChamberData(){
        if(null == userUnionChamberData){
            UserUnionChamberData chamberData = new UserUnionChamberData();
            chamberData.setUserId(player.getUserId());
            chamberData.setLastResetTime(System.currentTimeMillis() / 1000);
            chamberData.setUseHuntUserIdList(new ArrayList<>());
            chamberData.setInsertOption();
            userUnionChamberData = chamberData;
        }
    }

    public void syncChamberData(){
        UnionProto.UnionChamberDataMsg.Builder msg = UnionPb.parseUnionChamberDataMsg(userUnionChamberData);
        if(null != msg){
            player.sendPacket(Protocol.U_UNION_CHAMBER_DATA_SYNC, msg);
        }
    }

    public void syncChamberPatronsList(){
        String unionUid = player.getUserInfo().getUnionUid();
//        List<UserPatrons> patronsList = new ArrayList<>();
//        if(!StringUtils.isNullOrEmpty(unionUid)) {
//            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
//            if(null != memberMap) {
//                for(UnionMember unionMember : memberMap.values()){
//                    if(null != unionMember.getChamberPatron()){
//                        patronsList.add(unionMember.getChamberPatron());
//                    }
//                }
//            }
//        }
        List<CrossUnionChamberPatrons> patronsList = new ArrayList<>();
        if(!StringUtils.isNullOrEmpty(unionUid)) {
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            if(null != memberMap) {
                for(CrossUnionMember unionMember : memberMap.values()){
                    if(null != unionMember.getChamberPatrons() && unionMember.getChamberPatronsId() > 0){
                        patronsList.add(unionMember.getChamberPatrons());
                    }
                }
            }
        }
        player.sendPacket(Protocol.U_UNION_CHAMBER_PATRONS_LIST, CrossUnionPb.parseCrossUnionChamberPatronsListMsg(patronsList));
    }

    public void syncUnionMember(UnionMember unionMember){
        UnionProto.UnionMemberTempMsg.Builder msg = UnionPb.parseUnionMemberTempMsg(unionMember);
        if(null != msg){
            player.sendPacket(Protocol.U_UNION_MEMBER_SYNC, msg);
        }
    }

    public void addApplyUnionUid(String unionUid){
        CrossUnionMember member = CrossUnionMgr.getUnionMember("", player.getUserId());
        if(null == member){
            member = new CrossUnionMember();
            member.setUnionUid("");
            member.setUserId(player.getUserId());
            member.setUserBaseInfo(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId()));
            member.setInsertOption();
            CrossUnionMgr.addMemberToDeleteMap(member);
        }
        member.addApplyUnionUid(unionUid);
        syncUnionMember(member);
    }

    public void addUnionExp(long exp, eLogMoneyType master, eLogMoneyType son) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            //CrossUnionMgr.addUnionExp(player, unionUid, exp, master, son);
            player.notifyListener(eGamePlayerEventType.UnionExpRiseRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(exp), unionUid));

            CrossUnionMgr.addReward(player.getUserInfo(), GameConfig.GAME_ITEM_UNION_EXP, exp, son.getValue(), 1);
        }
    }

    public void addUnionWealth(long wealth, eLogMoneyType master, eLogMoneyType son) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            //CrossUnionMgr.addUnionWealth(player, unionUid, wealth, master, son);
            CrossUnionMgr.addReward(player.getUserInfo(), GameConfig.GAME_ITEM_UNION_WEALTH, wealth, son.getValue(), 1);
        }
    }

    public boolean isUnionWealthEnough(long value){
        long nowValue = 0;
        String unionUid = player.getUserInfo().getUnionUid();
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo != null) {
            nowValue = unionInfo.getWealth();
        }
        BigInteger preReduceValue = player.getModule(PreReduceModule.class).getPreReduceItemMap().get(GameConfig.GAME_ITEM_UNION_WEALTH);
        if (null == preReduceValue) {
            preReduceValue = BigInteger.ZERO;
        }
        long temp = preReduceValue.longValue();
        return nowValue + temp >= value;
    }

    public long removeUnionWealth(long wealth, eLogMoneyType master, eLogMoneyType son) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            //return CrossUnionMgr.removeUnionWealth(player, unionUid, wealth, master, son);
        }
        CrossUnionMgr.addReward(player.getUserInfo(), GameConfig.GAME_ITEM_UNION_WEALTH, wealth, son.getValue(), 0);
        return 0;
    }

    public long addContribution(long value, eLogMoneyType master, eLogMoneyType son) {
        if (value > 0) {
            String unionUid = player.getUserInfo().getUnionUid();
            UnionMember unionMember = CrossUnionMgr.getUnionMember(unionUid, player.getUserId());
            if (null != unionMember) {
                //先加缓存，同步跨服成功后，会覆盖，无妨
                unionMember.setContribution(unionMember.getContribution() + value);
//                unionMember.setContribution(unionMember.getContribution() + value);
//                unionMember.setTotalContribution(unionMember.getTotalContribution() + value);
//                unionMember.setTodayContribution((int) (unionMember.getTodayContribution() + value));
//                syncUnionMember(unionMember);
            }
            CrossUnionMgr.addReward(player.getUserInfo(), GameConfig.GAME_ITEM_UNION_CONTRIBUTION, value, son.getValue(), 1);
            return value;
        }
        return 0;
    }

    public long removeContribution(long value, eLogMoneyType master, eLogMoneyType son) {
        if (value > 0) {
            CrossUnionMgr.addReward(player.getUserInfo(), GameConfig.GAME_ITEM_UNION_CONTRIBUTION, value, son.getValue(), 0);
            String unionUid = player.getUserInfo().getUnionUid();
            UnionMember unionMember = CrossUnionMgr.getUnionMember(unionUid, player.getUserId());
            if (unionMember != null && unionMember.getContribution() >= value) {
//                long oldContribution = unionMember.getContribution();
                //先加缓存，同步跨服成功后，会覆盖，无妨
                unionMember.setContribution(unionMember.getContribution() - value);
//                syncUnionMember(unionMember);
//                return value;
            }
        }
        return 0;
    }

    public boolean isContributionEnough(long value){
        long nowValue = 0;
        String unionUid = player.getUserInfo().getUnionUid();
        UnionMember unionMember = CrossUnionMgr.getUnionMember(unionUid, player.getUserId());
        if (unionMember != null) {
            nowValue = unionMember.getContribution();
        }
        BigInteger preReduceValue = player.getModule(PreReduceModule.class).getPreReduceItemMap().get(GameConfig.GAME_ITEM_UNION_CONTRIBUTION);
        if (null == preReduceValue) {
            preReduceValue = BigInteger.ZERO;
        }
        long temp = preReduceValue.longValue();
        return nowValue + temp >= value;
    }

    public UserUnionChamberData getUserUnionChamberData() {
        return userUnionChamberData;
    }

    public int canQuitUnion(){
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        if (!StrongholdActivityMgr.isGameFinish()) {
            return GameErrorCode.E_STRONGHOLD_CAN_NOT_QUIT;
        }
        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        if (null != activityInfo) {//跨服商战进行时不能退出商会
            return GameErrorCode.E_UNION_CROSS_TRADE_WAR_CAN_NO_QUIT;
        }
        if(!SeacraftSouthSeaMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_CAN_NOT_QUIT;
        }
        if (!SeacraftPirateRiotMgr.canOperateUnion()) {
            return GameErrorCode.E_SEACRAFT_PIRATE_RIOT_CAN_NOT_QUIT_UNION;
        }
        if (!TongBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TONG_BING_CAN_NOT_QUIT_UNION;
        }
        if (!TonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TON_BING_CAN_NOT_QUIT_UNION;
        }
        if (!ChannelTonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_CTON_BING_CAN_NOT_QUIT_UNION;
        }
        if (!FiveHeroMgr.canChangeUnion()) {
            return GameErrorCode.E_FIVE_HERO_CAN_NOT_QUIT_UNION;
        }
        if (!TombMgr.canChangeUnion()){
            return GameErrorCode.E_TOMB_ACTIVITY_CAN_NO_QUIT;
        }
        // 大航海商会限制
        if (!HangHaiMgr.canChangeUnion()) {
            return GameErrorCode.E_HANGHAI_ACTIVITY_CAN_NOT_QUIT_UNION;
        }

        if (!OreWarActivityMgr.canChangeUnion()) {
            return GameErrorCode.E_ORE_WAR_CROSS_CAN_NO_QUIT_UNION;
        }

        // 群英
//        long now = System.currentTimeMillis() / 1000;
//        for (UnionWar unionWar : UnionPhaseWarMgr.getUnionWarMap().values()) {
//            if (now > unionWar.getActivityInfo().getEndTime() + 5 * 60) {
//                continue; // 热更：领奖期可以退商会
//            }
//            if (!unionWar.canDeleteUnion(unionUid)) {
//                return GameErrorCode.E_UNION_WAR_ACTIVITY_CAN_NOT_QUIT_UNION;
//            }
//        }

        if (!PeakStrongholdActivityMgr.canChangeUnion(unionUid)) {
            return GameErrorCode.E_PEAK_HOLD_CAN_NOT_QUIT_UNION;
        }
        if(!PeakSeacraftMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_PEAK_SEACRAFT_CAN_NOT_QUIT;
        }
        if (!LangYaBangMgr.canChangeUnion()){
            return GameErrorCode.E_LANG_YA_BANG_CAN_NO_QUIT_UNION;
        }
        if (!TwinsMgr.canChangeUnion()){
            return GameErrorCode.E_TWINS_CAN_NO_QUIT_UNION;
        }

        int ret = UnionActivityMgr.canChangeUnion();
        if (ret != 0) {
            return ret;
        }
        return 0;
    }

    public int canDeleteUnion(){
        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        String unionUid = player.getUserInfo().getUnionUid();
        if (null != activityInfo) {//跨服商战进行时不能解散商会
            return GameErrorCode.E_UNION_CROSS_TRADE_WAR_CAN_NO_DELETE;
        }
        if (!StrongholdActivityMgr.isGameFinish()) {
            return GameErrorCode.E_STRONGHOLD_CAN_NOT_DELETE;
        }
        if(!SeacraftSouthSeaMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_SEACRAFT_SOUTH_SEA_ACTIVITY_DELETE;
        }
        if(!UnionPhaseWarMgr.canDeleteUnion(unionUid)){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_CAN_NO_DELETE;
        }
        if(!RankUnionWarMgr.canDelUnion(unionUid)){
            return GameErrorCode.E_RANKUNIONWAR_ACTIVITY_DELETE;
        }
        if (!SeacraftPirateRiotMgr.canOperateUnion()) {
            return GameErrorCode.E_SEACRAFT_PIRATE_RIOT_CAN_NOT_DELETE_UNION;
        }
        if (!TongBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TONG_BING_CAN_NOT_DELETE_UNION;
        }
        if (!TonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_TON_BING_CAN_NOT_DELETE_UNION;
        }
        if (!ChannelTonBingMgr.canChangeUnion()) {
            return GameErrorCode.E_CTON_BING_CAN_NOT_DELETE_UNION;
        }
        if (!FiveHeroMgr.canChangeUnion()) {
            return GameErrorCode.E_FIVE_HERO_CAN_NOT_DELETE_UNION;
        }
        if (!TombMgr.canChangeUnion()){
            return GameErrorCode.E_TOMB_ACTIVITY_CAN_NO_DELETE;
        }
        // 大航海商会限制
        if (!HangHaiMgr.canChangeUnion()) {
            return GameErrorCode.E_HANGHAI_ACTIVITY_CAN_NOT_DELETE_UNION;
        }

        //巅峰据点战
        if (!PeakStrongholdActivityMgr.canChangeUnion(unionUid)) {
            return GameErrorCode.E_PEAK_HOLD_CAN_NOT_DELETE_UNION;
        }
        if(!PeakSeacraftMgr.canInAndOutUnion(unionUid)){
            return GameErrorCode.E_PEAK_SEACRAFT_DELETE;
        }
        if (!LangYaBangMgr.canChangeUnion()) {
            return GameErrorCode.E_LANG_YA_BANG_CAN_NO_DELETE_UNION;
        }

//        int ret = UnionActivityMgr.canChangeUnion();
//        if (ret != 0) {
//            return ret;
//        }

        List<ActivityInfo> showTimeActivityInfoList = NormalActivityMgr.getShowTimeActivityInfoList();
        for (ActivityInfo info : showTimeActivityInfoList) {
            if (!ActivityMgr.activityBeforeEndTime(info)) {
                continue;
            }
            eUnionActivityGroupType type = eUnionActivityGroupType.getType(info.getType());
            if (type == null) {
                continue;
            }
            //不是所名单的处理
            if (!type.isLockMember()) {
                //这个活动类型需要分组 并且 活动还没结束
                if (UnionActivityGroupHelper.needGroup(info) && ActivityMgr.activityBeforeEndTime(info)) {
                    boolean haveGroup = GameUnionActivityGroupMgr.haveGroup(info.getActivityId());
                    if (haveGroup) {
                        return GameErrorCode.E_UNION_ACTIVITY_GROUP_CAN_NOT_CHANGE_UNION;
                    }
                }
            } else {
                List<Integer> paramList = StringUtils.stringToIntegerList(info.getUnionGroup(), "\\|");
                if (paramList.size() >=4) {
                    long startGroupTime = info.getBeginShowTime() * 1000 + paramList.get(2) * DateHelper.MINUTE_MILLIONS;
                    long endGroupTime = info.getBeginShowTime() * 1000 + paramList.get(3) * DateHelper.MINUTE_MILLIONS;
                    long currentSecond = DateHelper.getCurrentTime() / 1000;
                    if (currentSecond >= startGroupTime && currentSecond <= endGroupTime) {
                        return GameErrorCode.E_UNION_ACTIVITY_GROUP_CAN_NOT_CHANGE_UNION;
                    }
                }
                UnionActivityGroupUnion unionData = GameUnionActivityGroupMgr.getUnionData(info.getActivityId(), unionUid);
                if (unionData != null) {
                    return GameErrorCode.E_UNION_ACTIVITY_GROUP_CAN_NOT_CHANGE_UNION;
                }
            }
        }

        if (!OreWarActivityMgr.canChangeUnion()) {
            return GameErrorCode.E_ORE_WAR_CROSS_CAN_NO_DELETE_UNION;
        }
        if (!TwinsMgr.canChangeUnion()) {
            return GameErrorCode.E_TWINS_CAN_NO_QUIT_UNION;
        }

        return 0;
    }

    public int constructUnion(int constructType) {

        UnionConstructConfig unionConstructConfig = UnionConfigMgr.getUnionConstructConfig(constructType);
        if (null == unionConstructConfig) {
            return GameErrorCode.E_UNION_CONSTRUCT_TYPE_ERROR;
        }

        //消耗
        boolean needConsume = true;
        if (2 == constructType) {
            if (player.getModule(CardModule.class).isUnionConstructMidFree()) {
                needConsume = false;
            }
        } else if (3 == constructType) {
            if (player.getModule(CardModule.class).isUnionConstructSupFree()) {
                needConsume = false;
            }
        }

        CrossUnionProto.UnionConstructionCrossReqMsg.Builder crossReq = CrossUnionProto.UnionConstructionCrossReqMsg.newBuilder();
        if (needConsume) {
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(unionConstructConfig.getConsume())) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            crossReq.setConsume(PropertyHelper.parsePropertyToString(unionConstructConfig.getConsume()));
            player.getModule(PreReduceModule.class).preReduce(unionConstructConfig.getConsume());
        }
        crossReq.setConstructionType(constructType);
        player.sendPacket(Protocol.C_UNION_CONSTRUCTION, crossReq);
        return 0;
    }

    public void freeConstructUnion(int constructType){
        CrossUnionProto.UnionConstructionCrossReqMsg.Builder crossReq = CrossUnionProto.UnionConstructionCrossReqMsg.newBuilder();
        crossReq.setConstructionType(constructType);
        player.sendPacket(Protocol.C_UNION_CONSTRUCTION, crossReq);
    }

    public UnionConstructResult preConstructUnion(int constructType) {
        UnionConstructResult result = new UnionConstructResult();
        UnionConstructConfig unionConstructConfig = UnionConfigMgr.getUnionConstructConfig(constructType);
        if (null == unionConstructConfig) {
            result.setRet(GameErrorCode.E_UNION_CONSTRUCT_TYPE_ERROR);
            return result;
        }

        //消耗
        boolean needConsume = true;
        if (2 == constructType) {
            if (player.getModule(CardModule.class).isUnionConstructMidFree()) {
                needConsume = false;
            }
        } else if (3 == constructType) {
            if (player.getModule(CardModule.class).isUnionConstructSupFree()) {
                needConsume = false;
            }
        }

        if (needConsume) {
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(unionConstructConfig.getConsume())) {
                result.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                return result;
            }
            result.setConsume(unionConstructConfig.getConsume());
            player.getModule(PreReduceModule.class).preReduce(unionConstructConfig.getConsume());
        }
        result.setRet(0);
        return result;
    }

    public Property handleConstructFromCross(int constructType, String consume, int ret) {

        Property reward = new Property();

        if(!StringUtils.isNullOrEmpty(consume)){
            player.getModule(PreReduceModule.class).restorePreReduce(consume);
        }

        if(ret == 0){
            //建设消耗
            if(!StringUtils.isNullOrEmpty(consume)){
                player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(consume), eLogMoneyType.Union, eLogMoneyType.UnionConstruct);
            }

            UnionConstructConfig unionConstructConfig = UnionConfigMgr.getUnionConstructConfig(constructType);
            if(unionConstructConfig != null){
                //奖励
                reward.addProperty(GameConfig.GAME_ITEM_UNION_CONTRIBUTION, BigInteger.valueOf(unionConstructConfig.getAddContribution()));
                reward.addProperty(GameConfig.GAME_ITEM_UNION_EXP, BigInteger.valueOf(unionConstructConfig.getAddUnionExp()));
                reward.addProperty(GameConfig.GAME_ITEM_UNION_WEALTH, BigInteger.valueOf(unionConstructConfig.getAddUnionWealth()));
                //奖励入口袋
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Union, eLogMoneyType.UnionConstruct);
            }

            AttributeModule attributeModule = player.getModule(AttributeModule.class);
            attributeModule.addAttribute(ePlayerAttrType.UnionTotalConstructTimes, 1);

            //任务、成就
            player.notifyListener(eGamePlayerEventType.UnionConstructTimes.getValue(), 1);
            player.notifyListener(eGamePlayerEventType.UnionUnionConstructTimes.getValue(), new UnionActivityTaskArgs(UnionActivityTaskArgs.TYPE_ADD_VALUE, 1, player.getUserInfo().getUnionUid()));
            player.notifyListener(eGamePlayerEventType.UnionTotalConstructTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.UnionTotalConstructTimes));
        }

        return reward;
    }

    public RecoveryRewardProto.UnionConstructResp.Builder recoveryUnionConstruct(int days,int discountParam) {
        List<Integer> needRecoveryType = new ArrayList<>();
        needRecoveryType.add(1);
        if (player.getModule(CardModule.class).isUnionConstructMidFree()) {
            needRecoveryType.add(2);
        }
        if (player.getModule(CardModule.class).isUnionConstructSupFree()) {
            needRecoveryType.add(3);
        }
        RecoveryRewardProto.UnionConstructResp.Builder unionBuilder = RecoveryRewardProto.UnionConstructResp.newBuilder();
        for (Integer type : needRecoveryType) {
            RecoveryRewardProto.UnionConstructData.Builder builder = RecoveryRewardProto.UnionConstructData.newBuilder();
            Property reward = new Property();
            UnionConstructConfig unionConstructConfig = UnionConfigMgr.getUnionConstructConfig(type);
            int timeThisType = 0;
            if (unionConstructConfig != null) {
                timeThisType = days * unionConstructConfig.getMaxTimes();
                builder.setType(type);
                //奖励
                int total = unionConstructConfig.getAddContribution() * timeThisType * discountParam / 1000;
                reward.addProperty(GameConfig.GAME_ITEM_UNION_CONTRIBUTION, BigInteger.valueOf(total));
                builder.setTimes(timeThisType);
                builder.setReward(PropertyHelper.parsePropertyToString(reward));
                //奖励入口袋
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Union, eLogMoneyType.UnionConstruct);
            }

            AttributeModule attributeModule = player.getModule(AttributeModule.class);
            attributeModule.addAttribute(ePlayerAttrType.UnionTotalConstructTimes, timeThisType);
            unionBuilder.addData(builder);

            //任务、成就
//            player.notifyListener(eGamePlayerEventType.UnionConstructTimes.getValue(), timeThisType);
//            player.notifyListener(eGamePlayerEventType.UnionUnionConstructTimes.getValue(), new UnionActivityTaskArgs(UnionActivityTaskArgs.TYPE_ADD_VALUE, timeThisType, player.getUserInfo().getUnionUid()));
            player.notifyListener(eGamePlayerEventType.UnionTotalConstructTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.UnionTotalConstructTimes));
        }
        return unionBuilder;
    }
}
